package ug.co.icom.kyazze.healthticket.services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ug.co.icom.kyazze.healthticket.mongoHQ.JSONParser;
import android.app.Activity;
import android.app.IntentService;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.AsyncTask;



public class IntentMySqlGetPublicKeyService extends IntentService {
	private static final String TAG ="MySqlGetPublicKey";
	@SuppressWarnings("unused")
	private Context context;
	private static String get_main_table = "http://appitconsult.com/healthticket/h_scripts/get_public_key.php";
	private static final String TAG_RESULT_ARRAY = "key_result";
	private static final String TAG_PUBLIC_KEY = "public_key";
	private static final String TAG_SUCCESS = "success";
	private String returned_public_key;
	private String filepath = "healthTicket_files";
	File directory;


	public IntentMySqlGetPublicKeyService() {
		super(TAG);
	}
	
	

	@Override
	protected void onHandleIntent(Intent intent) {
		ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
		directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
		
		downloadPubKey a_task = new downloadPubKey();
		a_task.execute("17");
		
	}

	
	
	private class downloadPubKey extends AsyncTask<String, String, String>{
		
		@SuppressWarnings("unused")
		Activity MainActivity;
		JSONParser jParser = new JSONParser();
		JSONArray key_result = null;
		

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			params.add(new BasicNameValuePair("phone_number", args[0]));

			JSONObject json = jParser.makeHttpRequest(get_main_table, "GET", params);
			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					key_result = json.getJSONArray(TAG_RESULT_ARRAY);

					// looping through All Products
					for (int i = 0; i < key_result.length(); i++) {
						JSONObject c = key_result.getJSONObject(i);
						// Storing each json item in variable
						String publickey = c.getString(TAG_PUBLIC_KEY );
						returned_public_key = publickey;	
						ApplicationObject app = (ApplicationObject) getApplication();
						app.setPublic_key(publickey);
						
					}
					
					
					
					try {
						URL url = new URL(returned_public_key);

						// create the new connection
						HttpURLConnection urlConnection = (HttpURLConnection) url
								.openConnection();
						urlConnection.setRequestMethod("GET");
						urlConnection.setDoOutput(true);
						urlConnection.connect();

						// set save path
						File SDCardRoot = new File(directory+"/");
						File file = new File(SDCardRoot, "17pubkey");

						FileOutputStream fileOutput = new FileOutputStream(file);
						InputStream inputStream = urlConnection.getInputStream();

						// create a buffer...

						byte[] buffer = new byte[1024];
						int bufferLength = 0; // used to store a temporary size of the
												// buffer

						// now, read through the input buffer and write the contents to
						// the file

						while ((bufferLength = inputStream.read(buffer)) > 0)

						{

							fileOutput.write(buffer, 0, bufferLength);


						}

						// close the output stream when done

						fileOutput.close();

					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
				} 

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return returned_public_key;

		}


		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
		

	}
	
	
//	private class saveDownload extends AsyncTask<String, Void, String> {
//		
//
//		@Override
//		protected String doInBackground(String... params) {
//			ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
//			directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
//
//			return null;
//		}
//
//	}


}

